package com.blue.base.security.exception;

import com.blue.base.common.bean.resp.JsonResult;
import com.blue.base.security.api.AuthService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 身份认证成功处理器
 *
 * @author liulei
 * @version 1.0
 */
@Slf4j
@AllArgsConstructor
public class AuthSuccessLoginHandler extends SimpleUrlAuthenticationSuccessHandler {

    private AuthService authService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        logger.info("用户身份认证成功...");

        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String token = this.authService.generateTokenByAccount(userDetails);


        // 设置用户登录上下文信息
        SecurityContextHolder.getContext().setAuthentication(authentication);
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JsonResult.ok(token).toString());
    }
}
